<template>
  <div>
    <!--报价-->
    <el-dialog
      title="我要报价"
      :visible.sync="dialogVisible11"
      :before-close="handleClose11"
      width="800px"
    >
      <div>
        <el-form
          size="mini"
          :model="sendForm11"
          label-width="140px"
          ref="sendForm11"
          :rules="rules11"
        >
          <div style="color:Red;text-align: left;margin-bottom: 10px;padding-left: 45px" v-if="score  !=='' && score < 80">询价商品竞争力小于80分！</div>
          <el-row>
            <el-col :span="12">
              <el-form-item label="报价：" prop="purchasePrice">
                <el-input
                  style="width: 200px"
                  type="number"
                  v-model="sendForm11.purchasePrice"
                  clearable
                ></el-input>
                <el-button type="text" style="margin-left: 5px" @click="showPriceList">往期报价</el-button>
                <div v-if="sendForm11.purchasePrice>0
            &&(categoryMinPrice > 0 || categoryMaxPrice > 0)
            && (sendForm11.purchasePrice < categoryMinPrice || sendForm11.purchasePrice > categoryMaxPrice)"
                     style="color: red;font-size:10px;">
                  未在产品线参考价格范围内
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="采购成本价：" prop="costPrice">
                <el-input
                  style="width: 200px"
                  type="number"
                  v-model="sendForm11.costPrice"
                  clearable
                ></el-input>
                <div
                  v-if="sendForm11.purchasePrice > 0 && sendForm11.costPrice > 0"
                  style="color: red;font-size:12px;">
                  采购吨毛利：{{ sendForm11.purchasePrice|fifterNumber(sendForm11.costPrice) }}
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="供货方：" prop="fromCompany">
                <el-select
                  v-model="sendForm11.fromCompany"
                  filterable
                  placeholder="请选择"
                  clearable
                  @change="handleWarehouseId"
                >
                  <el-option
                    v-for="item in fromCompanyList"
                    :key="item.fromCompanyId"
                    :label="item.fromCompanyName"
                    :value="item.fromCompanyName"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="发货仓库：" prop="warehouseName">
                <el-select
                  v-model="sendForm11.warehouseName"
                  filterable
                  placeholder="请选择"
                  clearable
                  @change="handleSendAreaId"
                >
                  <el-option
                    v-for="item in warehouseLists"
                    :key="item.warehouseId"
                    :label="item.warehouseName"
                    :value="item"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="发货地：" width="150" prop="sendAreaId">
                <el-cascader
                  ref="sendAreaId"
                  filterable
                  clearable
                  v-model="sendForm11.sendAreaId"
                  :props="{
                value: 'areaId',
                label: 'areaName',
                children: 'children',
              }"
                  :options="options"
                >
                </el-cascader>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="发货时间：" width="150" prop="sendDate">
                <el-date-picker
                  :picker-options="pickerOptions1"
                  v-model="sendForm11.sendDate"
                  value-format="yyyy-MM-dd"
                  type="date"
                  placeholder="选择日期"
                >
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="发货完成时间：" width="150" prop="endSendDate" v-if="isPreorder == 1 || isBatchPaid == 1" :key="10">
                <el-date-picker
                  :picker-options="pickerOptions1"
                  v-model="sendForm11.endSendDate"
                  value-format="yyyy-MM-dd"
                  type="date"
                  placeholder="选择日期"
                >
                </el-date-picker>
              </el-form-item>
              <el-form-item label="发货完成时间：" width="150" v-else :key="11">
                <el-date-picker
                  :picker-options="pickerOptions1"
                  v-model="sendForm11.endSendDate"
                  value-format="yyyy-MM-dd"
                  type="date"
                  placeholder="选择日期"
                >
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="交货方式：" width="150" prop="priceSendTypes">
                <el-radio-group
                  v-model="sendForm11.priceSendTypes"
                  @change="changeDeliveryType"
                >
                  <el-radio label="送到"></el-radio>
                  <el-radio label="自提"></el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="结算方式：" width="150" prop="pricePayTypes">
                <span>{{ pricePayTypes }}</span>
                <!-- <el-radio-group v-model="sendForm11.pricePayTypes">
                  <el-radio label="现汇"></el-radio>
                  <el-radio label="承兑"></el-radio>
                </el-radio-group> -->
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="价格类型：" width="150" prop="priceType">
                <el-select v-model="sendForm11.priceType">
                  <el-option label="滞销" value="滞销"></el-option>
                  <el-option label="紧俏" value="紧俏"></el-option>
                  <el-option label="平稳" value="平稳"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="发货类型：" width="150" prop="deliveryType">
                <el-select v-model="sendForm11.deliveryType">
                  <el-option label="公司发货" value="公司发货"></el-option>
                  <el-option label="客户自提" value="客户自提"></el-option>
                  <el-option
                    :disabled="deliveryDisabled"
                    label="采购发货"
                    value="采购发货"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="数量:" width="150" prop="priceNum">
                <el-input
                  v-model="sendForm11.priceNum"
                  type="number"
                  style="width: 200px"
                  :disabled="true"
                ></el-input>

              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="报价是否公开:" width="150">
                <el-select  v-model="sendForm11.isShowPrice">
                  <el-option :value="1" label="是"></el-option>
                  <el-option :value="0" label="否"></el-option>
                </el-select>

              </el-form-item>
            </el-col>
             <el-col :span="24">
               <el-form-item label="备注:">
                 <el-input
                   :placeholder="placeholder"
                   :autosize="{ minRows: 2, maxRows: 6}" type="textarea"
                   style="width: 90%"
                   v-model="sendForm11.priceRemark"
                 ></el-input>
               </el-form-item>
             </el-col>
          </el-row>
          <div>报价来源 <el-checkbox v-model="checked" style="padding-left:20px" @change="changeChecked">无来源</el-checkbox></div>
            <el-table
              :data="sendForm11.supplierPriceData"
              border
              size="mini"
              :header-cell-style="{ background: '#f8f8f9', color: '#80878f' }"
              style="width: 100%; margin-top: 20px"
              ref="table">
              <el-table-column align="center" label="供应商" min-width="220">
                <template slot-scope="scope">
                  <el-form-item label-width="0px"  :prop="`supplierPriceData.${scope.$index}.supplierId`" :rules="rules11.supplierId">
                    <el-select
                      v-model="scope.row.supplierId"
                      placeholder="请选择/输入"
                      style="width: 90%"
                      filterable
                      remote
                      reserve-keyword
                      :loading="loading"
                      :remote-method="(query) => remoteMethod(query, scope.row, scope.$index)"
                    >
                        <el-option
                          v-for="(item,index) in scope.row.supplierList"
                          :key="index"
                          :label="item.supplierName"
                          :value="item.supplierId">
                        </el-option>
                    </el-select>
                  </el-form-item>
                </template>
              </el-table-column>

              <el-table-column label="价格" align="center" min-width="120" >
                <template slot-scope="scope">
                  <el-form-item
                    label-width="0px"
                    :rules="rules11.supplierPrice"
                    :prop="`supplierPriceData.${scope.$index}.supplierPrice`"
                  >
                    <el-input
                      style="width: 90%"
                      clearable
                      type="number"
                      v-model="scope.row.supplierPrice"
                    ></el-input>
                  </el-form-item>
                </template>
              </el-table-column>

              <el-table-column
                label="操作"
                width="100"
                align="center"
              >
                <template slot-scope="scope">
                  <el-button type="text" size="mini" @click="delPrice(scope.$index)" v-if="scope.$index > 0">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
             <el-button type="text" size="small" @click="addPrice()" :disabled="checked">增加来源</el-button>

        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose11">取消</el-button>
        <el-button
          type="primary"
          @click="handleConfirm11"
          :loading="btnLoading11"
          >确认报价</el-button
        >
      </span>
    </el-dialog>

    <!--往期报价-->
    <el-dialog
      title="往期报价"
      :visible.sync="dialogVisible12"
      width="700px"
    >
      <div>
        <el-table
          v-loading="listLoading"
          :data="priceList"
          border
          style="width: 100%;">
          <el-table-column
            align="center"
            label="报价时间">
            <template slot-scope="scope">
              {{scope.row.priceTime}}
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            label="数量">
            <template slot-scope="scope">
              {{scope.row.priceNum}}
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            label="报价">
            <template slot-scope="scope">
              {{scope.row.purchasePrice}}
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            label="发货方式">
            <template slot-scope="scope">
              {{scope.row.priceSendTypes}}
            </template>
          </el-table-column>
        </el-table>

      </div>

    </el-dialog>
  </div>
</template>
<script>
import {
  getPriceList,
  getCustomerList,
  commitInquiryPrice,
  getAreaList,
  getFromCompanyList,
  warehouseList,
} from "@/api/allInLine/inquiry";
import { getGoodsList,beforeInquiryPriceList,getGoodsScore } from "@/api/allInLine/goods";
import{supplierListApi} from "@/api/allInLine/company";
import { mapGetters } from "vuex";
import { Message } from "element-ui";

const defaultSendForm11 = {
  inquiryId: "", //询价记录ID
  fromCompany: "", //供货方
  warehouseName: "", //发货仓库
  purchasePrice: "", //采购底价
  costPrice:"",//采购成本价
  sendAreaId: "", //发货区域ID
  sendDate: "", //发货时间
  priceSendTypes: "", //交货方式
  //pricePayTypes: "", //交易方式
  priceType: "", //价格类型
  deliveryType: "", //发货类型
  priceNum: "", //数量
  priceRemark: "", //备注
  isShowPrice:1,//报价是否公开
  endSendDate:'',//发货完成时间

  supplierPriceData:[],
};
const defaultPriceList = {
  supplierId:'',
  supplierPrice:''
}

export default {
  name: "addInquiryPrice",
  data() {
    return {
      dialogVisible11: false,
      btnLoading11: false,
      deliveryDisabled: false,
      sendForm11: JSON.parse(JSON.stringify(defaultSendForm11)),
      rules11: {
        purchasePrice: [
          { required: true, message: "请输入报价金额", trigger: "blur" },
        ],
        costPrice: [
          { required: true, message: "请输入采购成本价", trigger: "blur" },
        ],
        fromCompany: [
          { required: true, message: "请选择供货方", trigger: "change" },
        ],
        sendAreaId: [
          { required: true, message: "请选择发货地", trigger: "change" },
        ],
        warehouseName: [
          { required: true, message: "请选择发货仓库", trigger: "change" },
        ],
        sendDate: [
          { required: true, message: "请选择发货时间", trigger: "change" },
        ],
        priceSendTypes: [
          { required: true, message: "请选择交货方式", trigger: "change" },
        ],
        // pricePayTypes: [
        //   { required: true, message: "请选择支付方式", trigger: "change" },
        // ],
        priceType: [
          { required: true, message: "请选择价格类型", trigger: "change" },
        ],
        deliveryType: [
          { required: true, message: "请选择发货类型", trigger: "change" },
        ],
        // priceNum: [{ required: true, message: "请选择数量", trigger: "blur" }],
        supplierId: [
          { required: true, message: "请选择供应商", trigger: "change" },
        ],
        supplierPrice: [
          { required: true, message: "请选择输入价格", trigger: "blur" },
        ],
        endSendDate:[
          { required: true, message: "请选择发货完成时间", trigger: "change" },
        ]
      },
      companyQuerySearchList: [],
      goodsQuerySearchList: [],
      goodsList: [],
      warehouseLists: [], //仓库
      fromCompanyList: [], //供货方公司
      diQuIds: [],
      options: [],
      pickerOptions1: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7;
        },
      },
      categoryMinPrice: "",
      categoryMaxPrice: "",
      pricePayTypes:"",
      dialogVisible12:false,
      priceList:[],
      listLoading:false,
      score:'',
      loading:false,
      checked:false,
      isPreorder:'',
      isBatchPaid:'',
      placeholder:''
    };
  },
  computed: {
    ...mapGetters(["name", "mobile", "userId"]),
  },
  components: {},
  created() {
    // orderGoodsList().then((res)=>{
    //   this.goodsList = res.list
    // })
    this.getFromCompany();
  },
  filters: {
    fifterNumber(val1, val2) {
      let newval1 = val1 ? val1 : 0;
      let newval2 = val2 ? val2 : 0;
      return (newval1- newval2).toFixed(2)
    }
  },
  methods: {
    changeChecked(){
      if(this.checked){
        this.sendForm11.supplierPriceData = []
      }else{
        this.sendForm11.supplierPriceData = []
        this.addPrice()
      }
    },
    //获取供应商列表
    remoteMethod(query,scope,index) {
      if(query && query!= ''){
        this.loading = true;
        //获取供应产列表
        supplierListApi({tab:'all',supplierName:query,pageNum:1,pageSize:10000}).then(response => {
          let data = JSON.parse(JSON.stringify(scope));
          data.supplierList = response.list
          this.sendForm11.supplierPriceData.splice(index, 1, data);
          this.loading = false;
        }).catch(()=>{
          this.loading = false;
        });
      }
    },
    // 增加来源
    addPrice() {
      const data = JSON.parse(JSON.stringify(defaultPriceList));
      this.sendForm11.supplierPriceData.push(data);
    },
    delPrice(index) {
      this.sendForm11.supplierPriceData.splice(index, 1);
      // this.searchMemberList.splice(index, 1);
    },

    getScore(sapGoodsId){
      getGoodsScore({sapGoodsId}).then((res)=>{
        this.score = res.score
      })
    },
    showPriceList(){
      this.dialogVisible12 = true
      this.listLoading = true
      beforeInquiryPriceList({inquiryId:this.sendForm11.inquiryId}).then((res)=>{
          this.priceList = res.list
          this.listLoading = false
      }).catch(()=>{
        this.listLoading = false
      })
    },
    showPop9() {
      this.$refs.addGoodsSn.showPop();
    },
    showPop8() {
      this.$refs.addCustomer.showPop8();
    },

    changeDeliveryType() {
      if (this.sendForm11.priceSendTypes == "送到") {
        this.sendForm11.deliveryType = "采购发货";
        this.deliveryDisabled = false;
      } else if (this.sendForm11.priceSendTypes == "自提") {
        this.sendForm11.deliveryType = "";
        this.deliveryDisabled = true;
      }
    },

    //客户名称输入匹配
    companyQuerySearch(queryString) {
      if (queryString && queryString != "") {
        getCustomerList({ keywords: queryString }).then((res) => {
          this.companyQuerySearchList = res;
        });
      }
    },

    // 获取仓库名称
    handleWarehouseId(val) {
      this.sendForm11.warehouseName = '';
      this.sendForm11.sendAreaId = '';
      warehouseList({ fromCompany: val }).then((res) => {
        this.warehouseLists = res.list;
      });
    },

    handleSendAreaId(val) {
      this.sendForm11.sendAreaId = [val.provinceId, val.cityId, val.areaId];
      this.sendForm11.warehouseName = val.warehouseName;
    },

    //牌名输入匹配
    goodsQuerySearch(queryString) {
      if (queryString && queryString != "") {
        getGoodsList({
          keywords: queryString,
          categoryName: "",
          pageSize: "",
          pageNum: "",
        }).then((res) => {
          this.goodsQuerySearchList = res.list;
        });
      }
    },

    // 获取省市区列表
    getAddressListData() {
      getAreaList().then((res) => {
        this.options = res;
      });
    },

    //获取供货方列表
    getFromCompany() {
      getFromCompanyList().then((res) => {
        this.fromCompanyList = res;
      });
    },

    //显示询价
    showPop11(item) {
      this.categoryMinPrice = item.categoryMinPrice
      this.categoryMaxPrice = item.categoryMaxPrice
      this.sendForm11 = JSON.parse(JSON.stringify(defaultSendForm11));
      this.sendForm11.inquiryId = item.inquiryId;
      this.sendForm11.priceNum = item.goodsNum
      this.isPreorder = item.isPreorder
      this.isBatchPaid =item.isBatchPaid
      this.pricePayTypes=item.payTypes
      this.dialogVisible11 = true;
      this.deliveryDisabled = false;
      this.getAddressListData();
      this.score = ''
      this.getScore(item.sapGoodsId)
      this.checked = false
      this.addPrice()
      this.placeholder = (this.isPreorder == 1 || this.isBatchPaid == 1 )? '注明预售和多车订单可以接受的付款方式(全款/定金)' : ''
      // this.getMyCustomerName()
    },
    //关闭询价
    handleClose11() {
      this.$refs.sendForm11.resetFields();
      this.sendForm11 = JSON.parse(JSON.stringify(defaultSendForm11));
      this.dialogVisible11 = false;
    },

    //确认提交报价
    handleConfirm11() {
      this.$refs.sendForm11.validate( (valid) => {
        if (valid) {
          const data = JSON.parse(JSON.stringify(this.sendForm11));
          data.sendAreaId = data.sendAreaId
            ? data.sendAreaId[data.sendAreaId.length - 1]
            : "";
            this.btnLoading11 = true;
            data.supplierPriceData.forEach((el)=>{
              delete el.supplierList
            })
          commitInquiryPrice(data).then((res) => {
            if (res) {
              Message.success("提交成功");
              if (this.sendForm11.purchasePrice - this.sendForm11.costPrice <= -200) {
                this.$alert('您的报价中存在毛利过低', '提示', {
                  confirmButtonText: '关闭',
                });
              }
              this.btnLoading11 = false;
              this.$refs.sendForm11.resetFields();
              this.sendForm11 = JSON.parse(JSON.stringify(defaultSendForm11));
              this.$emit("update");
              this.dialogVisible11 = false;
            }
          }).catch(() => {
            this.btnLoading11 = false;
          })
        }
      });
    },
  },
};
</script>

<style  lang="scss">
</style>
